package com.itxh.core.excutor;

import com.itxh.core.config.BoundSql;
import com.itxh.core.config.Configuration;
import com.itxh.core.config.MappedStatement;
import com.itxh.core.handler.statement.RoutingStatementHandler;
import com.itxh.core.handler.statement.StatementHandler;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.util.List;

// 实现一级缓存处理
public class SimpleExecutor extends BaseExecutor{

    @Override
    protected <T> List<T> queryFromDataBase(MappedStatement mappedStatement, Configuration configuration, Object param) {
        Connection connection = null;
        Statement statement = null;
        try {
            // 获取连接
            DataSource dataSource = configuration.getDataSource();
            connection = dataSource.getConnection();
            // 获取StatementHandler
            String statementType = mappedStatement.getStatementType();
            StatementHandler statementHandler = new RoutingStatementHandler(statementType);
            // 获取Statement
            BoundSql boundSql = mappedStatement.getSqlSource().getBoundSql(param);
            statement = statementHandler.prepare(connection,boundSql.getSql());
            // 设置参数
            statementHandler.parameterize(statement,param,boundSql);

            // 执行Statement并获得返回结果
            return statementHandler.query(statement,boundSql,mappedStatement);


        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
